﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using BlogApi.Models;
using BlogApi.ModelsDto;
using BlogApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace BlogApi.Controllers
{
    [Route("api/comment")]
    [ApiController]
    public class CommentController : ControllerBase
    {
        private readonly ICommentRepository _commentRepository;
        private readonly IArticleRepository _articleRepository;
        private readonly IMapper _mapper;

        public CommentController(IArticleRepository articleRepository, ICommentRepository commentRepository,IMapper mapper)
        {
            _commentRepository = commentRepository ?? throw new ArgumentNullException(nameof(commentRepository));
            _articleRepository = articleRepository ?? throw new ArgumentNullException(nameof(articleRepository));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }
        [HttpPost]
        [Route("saveArticleComment")]
        public async Task<IActionResult> AddArticleComment([FromBody]CommentAddDto commentAddDto)
        {
            var commentEntity = _mapper.Map<Comment>(commentAddDto);
            _commentRepository.AddComment(commentEntity);
            var articleEntity = await _articleRepository.GetArticleAsync(commentAddDto.ArticleId);
            articleEntity.CommentNumber++;
            _articleRepository.UpdateArticle(articleEntity);
            if(await _commentRepository.SaveAsync())
            {

                return new JsonResult(new
                {
                    status = "ok",
                    newComment = await _commentRepository.GetCommentAndUserInfoAsync(commentEntity.Id)
                });
            }
            else
            {
                return BadRequest();
            }
        }
        [HttpGet]
        [Route("articleComment/{articleId}/{index}")]
        public async Task<IActionResult> GetArticleCommentList([FromRoute]Guid articleId,[FromRoute]int index)
        {
            var commentList = await _commentRepository.GetArticleCommentAndUserInfoDtosByPageAsync(articleId, 7, index);
            return new JsonResult(new
            {
                articleCommentList = commentList
            });
        }
    }
}